package org.example.processors;


import org.example.anotations.EnableAutoGenerateSql;
import org.example.anotations.TableInfo;

import javax.annotation.processing.*;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.Element;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.PackageElement;
import javax.lang.model.element.TypeElement;
import javax.tools.Diagnostic;
import java.util.HashSet;
import java.util.Set;


public abstract class SqlGeneratorProcessor extends AbstractProcessor {
    @Override
    public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
        for (Element element : roundEnv.getElementsAnnotatedWith(EnableAutoGenerateSql.class)) {
            if (element.getKind() == ElementKind.CLASS) {
                EnableAutoGenerateSql enableAutoGenerateSql = element.getAnnotation(EnableAutoGenerateSql.class);
                String[] basePackages = enableAutoGenerateSql.scanPackages();
                Set<TypeElement> elementsToProcess = new HashSet<>();
                for (String basePackage : basePackages) {
                    for (Element elem : roundEnv.getRootElements()) {
                        if (elem instanceof TypeElement) {
                            TypeElement typeElement = (TypeElement) elem;
                            PackageElement packageElement = processingEnv.getElementUtils().getPackageOf(typeElement);
                            if (packageElement.getQualifiedName().toString().startsWith(basePackage) && typeElement.getAnnotation(TableInfo.class) != null) {
                                elementsToProcess.add(typeElement);
                            }
                        }
                    }
                }

                for (TypeElement typeElement : elementsToProcess) {
                    processingEnv.getMessager().printMessage(Diagnostic.Kind.NOTE, "Processing class: " + typeElement.getQualifiedName());
                    generateSqlFile(typeElement);
                }
            }

        }
        return true;
    }

    protected abstract void generateSqlFile(TypeElement element);
}
